package ru.housewife.service.wares;

import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.form.*;
import ru.housewife.model.CookingDishComponent;
import ru.housewife.model.PreferableWareForComponent;
import ru.housewife.model.User;
import ru.housewife.model.Ware;

/**
 * TODO: add description
 * Date: 04.09.11 21:37
 *
 * @author Alexander Troshanin
 */
public class SetPreferableWareForRecipesComponent implements HibernateAction<Void> {

    private UserForm userForm;
    private long componentId;
    private WareForm wareForm;

    public SetPreferableWareForRecipesComponent(UserForm userForm, CookingDishComponentForm componentForm, WareForm wareForm) {
        this.userForm = userForm;
        this.componentId = componentForm.getId();
        this.wareForm = wareForm;
    }

    @Override
    public Void execute(Session session) {
        PreferableWareForComponentForm existingPrefWareForm = userForm.getPreferableWareForComponent(componentId);

        Ware ware = (Ware) session.get(Ware.class, wareForm.getId());
        if (existingPrefWareForm != null) {
            PreferableWareForComponent prefWare = (PreferableWareForComponent) session.get(PreferableWareForComponent.class, existingPrefWareForm.getId());
            if (prefWare != null && ware != null) {
                prefWare.setWare(ware);
                session.save(prefWare);

                // updating object in memory
                userForm.removePreferableWareForComponentFromUsersWares(existingPrefWareForm);
                existingPrefWareForm.setWare(wareForm);
                userForm.addPreferableWareForComponentToUsersWares(existingPrefWareForm);
            }
        } else {
            User user = (User) session.get(User.class, userForm.getId());
            CookingDishComponent component = (CookingDishComponent) session.get(CookingDishComponent.class, componentId);
            PreferableWareForComponent prefWare = new PreferableWareForComponent();
            if (user != null && ware != null && component != null) {
                prefWare.setUser(user);
                prefWare.setComponent(component);
                prefWare.setWare(ware);
                session.save(prefWare);

                PreferableWareForComponentForm prefWareForm = new PreferableWareForComponentForm();
                prefWareForm.setId(prefWare.getId());
                prefWareForm.setWare(wareForm);
                prefWareForm.setUser(userForm);
                prefWareForm.setComponentId(componentId);
                userForm.addPreferableWareForComponent(prefWareForm);
            }
        }
        return null;
    }
}
